package com.simpletour.qa.gateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.simpletour.qa.common.http.ObjectRestResponse;
import com.simpletour.qa.common.http.ResponseCode;
import com.simpletour.qa.common.http.ResponseMsg;
import com.simpletour.qa.gateway.exception.JwtNotExistException;
import com.simpletour.qa.gateway.exception.NoAuthorityException;
import com.simpletour.qa.gateway.util.HttpContextUtil;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.zuul.util.ZuulRuntimeException;
import org.springframework.stereotype.Component;

/**
 * 网关错误过滤器
 * @author zhaohw
 * @date 2018-06-20 17:54
 */
@Component
@Slf4j
public class GatewayErrorFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return "error";
    }


    @Override
    public int filterOrder() {
        // SendErrorFilter前
        return -1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        Exception e = (Exception)ctx.get("throwable");
        if (e instanceof ZuulException) {

            Throwable cause = e.getCause();
            // 删除异常信息,否则在下一个过滤器中还会被执行处理
            ctx.remove("throwable");
            log.error(cause.toString()+":"+cause.getMessage());

            if(cause instanceof JwtNotExistException){
                HttpContextUtil.sendOkResponse(ctx,ObjectRestResponse.builder()
                        .code(ResponseCode.JWT_NOT_EXIST)
                        .msg(ResponseMsg.JWT_NOT_EXIST));
            }

            else if(cause instanceof ExpiredJwtException){
                HttpContextUtil.sendOkResponse(ctx,ObjectRestResponse.builder()
                        .code(ResponseCode.JWT_IS_EXPIRED)
                        .msg(ResponseMsg.JWT_IS_EXPIRED));
            }
            else if(cause instanceof IllegalArgumentException){
                HttpContextUtil.sendOkResponse(ctx,ObjectRestResponse.builder()
                        .code(ResponseCode.JWT_PARAM_CHECK_ERROR)
                        .msg(ResponseMsg.JWT_PARAM_CHECK_ERROR));
            }
            else if(cause instanceof NoAuthorityException){
                HttpContextUtil.sendOkResponse(ctx,ObjectRestResponse.builder()
                        .code(ResponseCode.NO_AUTHORITY)
                        .msg(ResponseMsg.NO_AUTHORITY));
            }
            else if(cause instanceof ZuulRuntimeException){
                HttpContextUtil.sendOkResponse(ctx,ObjectRestResponse.builder()
                        .code(ResponseCode.SERVICE_INVOKE_ERROR)
                        .msg(ResponseMsg.SERVICE_INVOKE_ERROR));
            }

        }
        return null;
    }
}
